import { ref } from "vue";
import { useRoute } from "vue-router";
import { getCityByIp, getWeatherByAdcode, getTodayWeatherByAdcode } from "@/api/getData";

const useWeatherData = () => {
    const weather = ref(null);
    const futureWeather = ref(null);
    const city = ref(null);
    const getFutureWeather = async () => {
        const route = useRoute();
        try {
            if (route.path === "/weather/") {
                // 获取当前城市
                // 根据ip获取当前城市
                city.value = await getCityByIp();
                const res = await getWeatherByAdcode(city.value);
                futureWeather.value = res;
            } else {
                city.value = route.query.search;
                const res = await getWeatherByAdcode(route.params.cityCode);
                futureWeather.value = res;
            }
        } catch (err) {
            console.log("获取未来天气信息失败", err);
        }
        return futureWeather.value;
    };

    const getCurrentWeather = async () => {
        try{
            city.value = await getCityByIp();
            weather.value = await getTodayWeatherByAdcode(city.value);
        } catch (err) {
            console.log("获取当天天气信息失败", err);
        }

        return { weather: weather.value, city: city.value };
    };

    return {  getFutureWeather, getCurrentWeather };
};

export default useWeatherData;
